import React, { useCallback } from 'react';
import { Progress, Button, Space, Typography, Tooltip } from 'antd';
import {
  CloseOutlined,
  PlayCircleOutlined,
  PauseCircleOutlined,
  CheckCircleOutlined,
  ExclamationCircleOutlined,
  LoadingOutlined,
  WarningOutlined,
} from '@ant-design/icons';
import { UniversalNotification, useUniversalNotification } from '../contexts/UniversalNotificationContext';
import { useTheme } from '../contexts/ThemeContext';

const { Text } = Typography;

interface DynamicIslandItemProps {
  notification: UniversalNotification;
  index: number;
  isLast: boolean;
}

const DynamicIslandItem: React.FC<DynamicIslandItemProps> = ({
  notification,
  index,
  isLast,
}) => {
  const { update: updateNotification, remove: removeNotification } = useUniversalNotification();
  const { currentTheme, isDark } = useTheme();

  // 获取状态图标
  const getStatusIcon = useCallback(() => {
    const iconStyle = { fontSize: '12px' };
    
    switch (notification.status) {
      case 'running':
        return <LoadingOutlined style={{ ...iconStyle, color: '#1890ff' }} spin />;
      case 'success':
        return <CheckCircleOutlined style={{ ...iconStyle, color: '#52c41a' }} />;
      case 'error':
      case 'failed':
        return <ExclamationCircleOutlined style={{ ...iconStyle, color: '#ff4d4f' }} />;
      case 'warning':
        return <WarningOutlined style={{ ...iconStyle, color: '#faad14' }} />;
      case 'paused':
        return <PauseCircleOutlined style={{ ...iconStyle, color: '#8c8c8c' }} />;
      default:
        return <PlayCircleOutlined style={{ ...iconStyle, color: '#1890ff' }} />;
    }
  }, [notification.status]);

  // 获取状态颜色
  const getStatusColor = useCallback(() => {
    switch (notification.status) {
      case 'running':
        return '#1890ff';
      case 'success':
        return '#52c41a';
      case 'error':
      case 'failed':
        return '#ff4d4f';
      case 'warning':
        return '#faad14';
      case 'paused':
        return '#8c8c8c';
      default:
        return '#1890ff';
    }
  }, [notification.status]);

  // 获取文本颜色 - iOS风格统一使用白色文字
  const getTextColor = useCallback(() => {
    const isLightTheme = currentTheme.key === 'light' || currentTheme.key === 'green';
    return isLightTheme ? '#1f2937' : '#ffffff';
  }, [currentTheme.key]);

  // 获取次要文本颜色
  const getSecondaryTextColor = useCallback(() => {
    const isLightTheme = currentTheme.key === 'light' || currentTheme.key === 'green';
    return isLightTheme ? 'rgba(31, 41, 55, 0.7)' : 'rgba(255, 255, 255, 0.7)';
  }, [currentTheme.key]);

  // 处理关闭通知
  const handleClose = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    removeNotification(notification.id);
  }, [notification.id, removeNotification]);

  // 处理暂停/恢复
  const handleTogglePause = useCallback((e: React.MouseEvent) => {
    e.stopPropagation();
    const newStatus = notification.status === 'paused' ? 'running' : 'paused';
    updateNotification(notification.id, { status: newStatus });
  }, [notification.id, notification.status, updateNotification]);

  // 格式化时间
  const formatDuration = useCallback((startTime: number) => {
    const duration = Math.floor((Date.now() - startTime) / 1000);
    if (duration < 60) return `${duration}s`;
    if (duration < 3600) return `${Math.floor(duration / 60)}m`;
    return `${Math.floor(duration / 3600)}h`;
  }, []);

  return (
    <div
      className={`dynamic-island-item ${!isLast ? 'with-divider' : ''}`}
      style={{
        padding: '10px 16px',
        borderBottom: !isLast ? `1px solid rgba(255, 255, 255, 0.1)` : 'none',
        borderRadius: '8px',
        margin: '2px 0',
      }}
    >
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        {/* 左侧：状态图标和信息 */}
        <div style={{ display: 'flex', alignItems: 'center', flex: 1, minWidth: 0 }}>
          {getStatusIcon()}
          
          <div style={{ marginLeft: '8px', flex: 1, minWidth: 0 }}>
            {/* 标题 */}
            <Text
              strong
              style={{
                fontSize: '12px',
                color: getTextColor(),
                display: 'block',
                lineHeight: '16px',
                overflow: 'hidden',
                textOverflow: 'ellipsis',
                whiteSpace: 'nowrap',
              }}
            >
              {notification.title}
            </Text>
            
            {/* 描述或进度信息 */}
            {(notification.description || notification.progress !== undefined) && (
              <Text
                style={{
                  fontSize: '10px',
                  color: getSecondaryTextColor(),
                  display: 'block',
                  lineHeight: '14px',
                  overflow: 'hidden',
                  textOverflow: 'ellipsis',
                  whiteSpace: 'nowrap',
                }}
              >
                {notification.progress !== undefined 
                  ? `${notification.progress}% ${notification.description || ''}`
                  : notification.description
                }
              </Text>
            )}
          </div>
        </div>

        {/* 右侧：操作按钮 */}
        <Space size={4}>
          {/* 时间显示 */}
          <Text
            style={{
              fontSize: '9px',
              color: getSecondaryTextColor(),
              opacity: 0.8,
            }}
          >
            {formatDuration(notification.startTime)}
          </Text>

          {/* 暂停/恢复按钮 */}
          {notification.status === 'running' || notification.status === 'paused' ? (
            <Tooltip title={notification.status === 'paused' ? '恢复' : '暂停'}>
              <Button
                type="text"
                size="small"
                icon={notification.status === 'paused' ? <PlayCircleOutlined /> : <PauseCircleOutlined />}
                onClick={handleTogglePause}
                style={{
                  width: '24px',
                  height: '24px',
                  minWidth: '24px',
                  padding: 0,
                  fontSize: '12px',
                  color: getSecondaryTextColor(),
                  border: 'none',
                  borderRadius: '6px',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                }}
              />
            </Tooltip>
          ) : null}

          {/* 关闭按钮 */}
          <Tooltip title="关闭">
            <Button
              type="text"
              size="small"
              icon={<CloseOutlined />}
              onClick={handleClose}
              style={{
                width: '24px',
                height: '24px',
                minWidth: '24px',
                padding: 0,
                fontSize: '12px',
                color: getSecondaryTextColor(),
                border: 'none',
                borderRadius: '6px',
                display: 'flex',
                alignItems: 'center',
                justifyContent: 'center',
              }}
            />
          </Tooltip>
        </Space>
      </div>

      {/* 进度条 */}
      {notification.progress !== undefined && (
        <div style={{ marginTop: '6px' }}>
          <Progress
            percent={notification.progress}
            strokeColor={getStatusColor()}
            trailColor={isDark ? 'rgba(148, 163, 184, 0.2)' : 'rgba(0, 0, 0, 0.06)'}
            size="small"
            strokeWidth={2}
            showInfo={false}
          />
        </div>
      )}
    </div>
  );
};

export default DynamicIslandItem;
